/*
*
* Copyright 2013 Netflix, Inc.
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*
*/

package com.netflix.client.samples;

import java.net.URI;

import org.junit.Ignore;

import com.netflix.client.ClientFactory;
import com.netflix.client.http.HttpRequest;
import com.netflix.client.http.HttpResponse;
import com.netflix.config.ConfigurationManager;
import com.netflix.loadbalancer.ZoneAwareLoadBalancer;
import com.netflix.niws.client.http.RestClient;

@Ignore
public class SampleApp {

	public static void main(String[] args) throws Exception {
	    // archaius 的内部类，加载配置文件
        // Load the properties file using Archaius ConfigurationManager.
        ConfigurationManager.loadPropertiesFromResources("sample-client.properties");  // 1
        // 输出配置文件中 listOfServers 配置的服务器列表
        System.out.println("初始化的服务器列表：" + ConfigurationManager.getConfigInstance().getProperty("sample-client.ribbon.listOfServers"));
        // 基于配置的 client factory，获取 client
        // 使用 ClientFactory 创建 client 和 load balancer，此处就会加载内置的配置文件属性
        RestClient client = (RestClient) ClientFactory.getNamedClient("sample-client");  // 2
        // 构建一个 Http请求
        // 这里构建使用了 "/" 的 url，但是一旦 server 被 load balancer 选中后，url 会被动态计算出来
        HttpRequest request = HttpRequest.newBuilder().uri(new URI("/")).build(); // 3
        for (int i = 0; i < 20; i++)  {
            // 执行请求并输出响应
        	HttpResponse response = client.executeWithLoadBalancer(request); // 4
        	System.out.println("Status code for " + response.getRequestedURI() + "  :" + response.getStatus());
        }
        ZoneAwareLoadBalancer lb = (ZoneAwareLoadBalancer) client.getLoadBalancer();
        // 打印出负载均衡器记录的服务器统计信息。 stats(统计数据)
        System.out.println(lb.getLoadBalancerStats());

        // 动态改动 server pool，并非新增，而是修改整个 pool
        ConfigurationManager.getConfigInstance().setProperty(
        		"sample-client.ribbon.listOfServers", "www.linkedin.com:80,www.google.com:80"); // 5
        System.out.println("changing servers ...");
        // 等待 server pool 刷新，间隔在 sample-client.properties 的 ServerListRefreshInterval 配置了 2s
        Thread.sleep(3000); // 6
        System.out.println("动态设置后的服务器列表：" + ConfigurationManager.getConfigInstance().getProperty("sample-client.ribbon.listOfServers"));

        for (int i = 0; i < 20; i++)  {
        	HttpResponse response = client.executeWithLoadBalancer(request);
        	System.out.println("Status code for " + response.getRequestedURI() + "  : " + response.getStatus());
        }
        // 打印出负载均衡器记录的服务器统计信息。 stats(统计数据)
        /**
         * 区域统计
         * Zone stats: {unknown=[   Zone:unknown;
         *              Instance count:3;
         *              Active connections count: 0;
         *              Circuit breaker tripped count: 0;
         *              Active connections per server: 0.0;
         *          ]},
         *  服务器统计
         * Server stats: [
         *           [  Server:www.hao123.com:80;
         *              Zone:UNKNOWN;
         *              Total Requests:7;
         *              Successive(连续的) connection failure:0;
         *              Total blackout seconds:0;
         *              Last connection made:Sun Jul 25 14:33:59 CST 2021;
         *              First connection made: Sun Jul 25 14:33:55 CST 2021;
         *              Active Connections:0;
         *              total failure count in last (1000) msecs:0;
         *              average resp time:363.7142857142857;
         *              90 percentile resp time:452.0;
         *              95 percentile resp time:452.0;
         *              min resp time:290.0;
         *              max resp time:502.0;
         *              stddev resp time:80.52100752636676
         *          ],
         *          [   Server:www.baidu.com:80;
         *              Zone:UNKNOWN;
         *              Total Requests:6;
         *              Successive connection failure:0;
         *              Total blackout seconds:0;
         *              Last connection made:Sun Jul 25 14:33:59 CST 2021;
         *              First connection made: Sun Jul 25 14:33:55 CST 2021;
         *              Active Connections:0;
         *              total failure count in last (1000) msecs:0;
         *              average resp time:222.83333333333334;
         *              90 percentile resp time:196.0;
         *              95 percentile resp time:196.0;
         *              min resp time:196.0;
         *              max resp time:253.0;
         *              stddev resp time:17.780294960683033
         *          ],
         *          [   Server:www.4399.com:80;
         *              Zone:UNKNOWN;
         *              Total Requests:7;
         *              Successive connection failure:0;
         *              Total blackout seconds:0;
         *              Last connection made:Sun Jul 25 14:34:00 CST 2021;
         *              First connection made: Sun Jul 25 14:33:55 CST 2021;
         *              Active Connections:0;
         *              total failure count in last (1000) msecs:0;
         *              average resp time:209.28571428571428;
         *              90 percentile resp time:213.0;
         *              95 percentile resp time:213.0;
         *              min resp time:172.0;
         *              max resp time:269.0;
         *              stddev resp time:30.513295864095053
         *           ]]
         */
        System.out.println(lb.getLoadBalancerStats()); // 7
	}

}
